<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="查询内容" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="查询类型" clearable class="filter-item" style="width: 130px;margin-left: 10px;">
        <el-option v-for="item in searchTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加社团
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        下载数据
      </el-button>
      <el-checkbox v-model="listQuery.onlyWorking" style="margin-left: 10px" @change="getList">只显示活跃</el-checkbox>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="#ID" prop="id" sortable="custom" align="center" width="100" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公司名称" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="公司类型" width="300px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.label }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" width="100px">
        <template slot-scope="{row}">
          <span class="link-type" @click="toMember(row.id)"> {{ row.principal }} </span>
        </template>
      </el-table-column>
      <el-table-column label="成员" align="center" min-width="100px">
        <template slot-scope="{row}">
          <span> ————后续开发————</span>
        </template>
      </el-table-column>
      <el-table-column label="人数" align="center" width="205">
        <template slot-scope="{row}">
          <span> ————后续开发————</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
<!--            {{ row.status }}-->
            后续
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Actions" align="center" width="270" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="toDetail(row.id)">
            详情
          </el-button>
          <el-button size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
          <el-button circle icon="el-icon-chat-dot-round" style="background-color: #409EFF;color: white" @click="toChat(row)" />
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 90%; margin-left:50px;">
        <el-form-item label="社团名称:" prop="name">
          <el-input v-model="temp.name" style="width: 70%" />
        </el-form-item>
        <el-form-item label="社团级别:" prop="level">
          <el-select v-model="temp.level" class="filter-item" placeholder="请选择">
            <el-option v-for="item in levelOptions" :key="item.key" :label="item.display_name" :value="item.display_name" />
          </el-select>
        </el-form-item>
        <el-form-item label="社团状态:">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="社团简介:">
          <el-input v-model="temp.intro" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
        <div class="text-danger">*社团成员在详情处设置</div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <!--    deleteDialog-->
    <el-dialog title="删除确认" :visible.sync="deleteDialogFormVisible" style="width: 450px;margin: 0 auto">
      <div ref="dataForm" style="width: 100%;" class="text-danger">
        <span><i class="el-icon-warning-outline" /></span>
        删除数据将无法恢复
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelData">
          取消
        </el-button>
        <el-button type="danger" @click="deleteData">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchComList } from '@/api/com'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const searchTypeOptions = [
  { key: 'name', display_name: '社团名称' }
  // { key: 'level', display_name: '社团级别' }
]

const searchTypeKeyValue = searchTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '活跃': 'success',
        '暂停': 'info',
        '解散': 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return searchTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: '',
        type: '',
        onlyWorking: true
      },
      searchTypeOptions,
      levelOptions: [
        { key: '0', display_name: '兴趣社团' },
        { key: '1', display_name: '院级社团' },
        { key: '2', display_name: '校级社团' }
      ],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['活跃', '暂停', '解散'],
      showReviewer: false,
      temp: {
        id: '',
        name: '',
        position: '',
        level: '',
        num: '',
        principal: '',
        status: '',
        intro: '',
        logo: '',
        expenditure: 0
      },
      addDialogFormVisible: false,
      dialogFormVisible: false,
      deleteDialogFormVisible: false,
      deleteTemp: -1,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      // this.listLoading = true
      fetchComList(this.listQuery).then(res => {
        var list = res.data.items
        // for (const i in list) {
        //   list[i]['memberString'] = ''
        //   for (const j in list[i].members) {
        //     list[i]['memberString'] += list[i].members[j].name + ', '
        //   }
        //   list[i]['memberString'] = list[i].memberString.substring(0, list[i].memberString.lastIndexOf(','))
        // }
        this.list = list
        this.total = res.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 200)
      })
    },
    toDetail(id) {
      console.log(id)
      this.$router.push({ path: '/org-info/detail/' + id })
    },
    toMember(id) {
      this.$router.push({ path: '/member/detail/' + id + '/' + new Date().getTime() })
    },
    toChat(row) {
      this.$router.push({ path: '/inform/p2o/' + row.name + '/' + new Date().getTime() })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: '活跃',
        type: '',
        expenditure: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      const tempData = Object.assign({}, this.temp)
      createOrg(tempData).then((res) => {
        this.dialogFormVisible = false
        if (res.status === 200) {
          this.getList()
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      console.log(row)
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row, index) {
      this.deleteDialogFormVisible = true
    },
    updateData() {
      const tempData = Object.assign({}, this.temp)
      updateOrg(tempData).then((res) => {
        this.dialogFormVisible = false
        if (res.status === 200) {
          this.getList()
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    cancelData() {
      this.deleteDialogFormVisible = false
      this.deleteTemp = -1
    },
    deleteData() {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(this.deleteTemp, 1)
      this.deleteTemp = -1
      this.deleteDialogFormVisible = false
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['社团id', '社团名称', '社团级别', '社团人数', '负责人', '状态', '简介', 'logo']
        const filterVal = ['id', 'name', 'level', 'num', 'principal', 'status', 'intro', 'logo']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '社团信息表（总）'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
